package com.example.musicplayer.activity;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.example.musicplayer.R;
import com.example.musicplayer.adapter.SongSheetAdapter;
import com.example.musicplayer.bean.Album;
import com.example.musicplayer.bean.Song;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SongSheetActivity extends AppCompatActivity {
   private static final String TAG = "SongSheetActivity";
    private RecyclerView mRecyclerView;
    private SongSheetAdapter mMyAdapter;
    private List<Album> albumList;
    private Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_song_sheet);
        initView();
    }

    private void initView(){

        toolbar = findViewById(R.id.tb_activity_songsheet);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mRecyclerView = findViewById(R.id.rv_activity_songsheet);
        albumList = new ArrayList<>();
        mMyAdapter = new SongSheetAdapter(albumList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mMyAdapter);
        //网络请求
        String url = getString(R.string.web_ip)+"/list/all";
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String json = response.body().string();
                System.out.println(json);
                List<HashMap> list = JSON.parseArray(json, HashMap.class);
                for(int i=0;i<list.size();i++){
                    Album album  = new Album();
                    album.setName(list.get(i).get("name").toString());
                    album.setNumber(Integer.parseInt(list.get(i).get("number").toString()));
                    String url = getString(R.string.web_ip)+"/songs/all/"+list.get(i).get("id");
                    OkHttpClient okHttpClient = new OkHttpClient();
                    final Request request = new Request.Builder()
                            .url(url)
                            .get()
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            Log.d(TAG, "onFailure: 网络请求获取歌单全部歌曲失败");
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            Log.d(TAG, "onFailure: 网络请求获取歌单全部歌曲成功");
                            String json = response.body().string();
                            List<HashMap> list =JSON.parseArray(json, HashMap.class);
                            List<Song> songList = new ArrayList<Song>();
                            for(HashMap k:list){
                                Song oneSong = new Song();
                                oneSong.song = (String)k.get("song");
                                oneSong.singer = (String)k.get("singer");
                                oneSong.duration = (Integer) k.get("duration");
                                oneSong.path = (String) k.get("path");
                                oneSong.albumCoverPath = (String) k.get("album_cover_path");
                                oneSong.id = (Integer) k.get("id");
                                songList.add(oneSong);
                            }
                            album.setSongList(songList);
                            if(album.getSongList().isEmpty()){
                                album.setAlbumCover(getAlbumArt(0));
                            }else{
                                String url = getString(R.string.web_ip)+"/cover/"+album.getSongList().get(0).id;
                                album.setAlbumCover(getImageFromNetByUrl(url));
                            }
                            albumList.add(album);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mMyAdapter.notifyDataSetChanged();
                                }
                            });

                        }
                    });
                }
            }
        });



    }


    public List<String> getData(){
        List<String> list = new ArrayList<>();
        for(int i=0;i<100;i++){
            list.add("item :"+i);
        }
        return list;
    }


    private Bitmap getAlbumArt(long album_id) {
        String mUriAlbums = "content://media/external/audio/albums";
        String[] projection = new String[]{"album_art"};
        Cursor cur = getContentResolver().query(Uri.parse(mUriAlbums + "/" + Long.toString(album_id)), projection, null, null, null);
        String album_art = null;
        if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
            cur.moveToNext();
            album_art = cur.getString(0);
        }
        cur.close();
        Bitmap bm = null;
        if (album_art != null) {
            bm = BitmapFactory.decodeFile(album_art);
        } else {
            bm = BitmapFactory.decodeResource(getResources(), R.drawable.musicpic);
        }
        return bm;
    }

    private  Bitmap getImageFromNetByUrl(final String src){
        try {
            Log.d("FileUtil", src);
            URL url = new URL(src);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            connection.disconnect();
            return myBitmap;
        } catch (IOException e) {
            // Log exception
            return null;
        }

    }

}
